package com.gdth.utils;

import java.lang.reflect.Field;
import java.sql.Blob;
import java.util.List;

import com.gdth.core.annotation.table.Column;
import com.gdth.core.annotation.table.Id;

/**
 * Sql tools
 * @author Arvin
 *
 */
public class SqlUtil {

	/**
	 * According to the entity class to create a table
	 * @param arg0
	 * @return
	 */
	public static<T> String createTable(Class<?> arg0){
		String tableName = ClassUtil.getTableName(arg0);
		
		StringBuilder sb = new StringBuilder();
		sb.append("create table if not exists ").append(tableName).append("(");
		
		List<Field> mList_Field = ClassUtil.getFields(arg0.getDeclaredFields(), arg0.getSuperclass().getDeclaredFields());
		
		for (Field mField : mList_Field){
			if (!mField.isAnnotationPresent(Column.class)){
				continue;
			}
		
			Column mColumn = (Column) mField.getAnnotation(Column.class);
			
			String type = "";
			
			if (mColumn.type().equals(""))
				type = SqlUtil.getColumnType(mField.getType());
			else
				type = mColumn.type();
			
			sb.append(mColumn.name()).append(" ").append(type);
			
			if (mColumn.length() != 0){
				sb.append("(").append(mColumn.length()).append(")");
			}
			
			if (mField.isAnnotationPresent(Id.class) 
					&& (mField.getType() == Integer.class || mField.getType() == Integer.TYPE)){
				sb.append(" primary key autoincrement");
			}
			else if (mField.isAnnotationPresent(Id.class)){
				sb.append(" primary key");
			}
			
			sb.append(",");
		}
		
		sb.delete(sb.lastIndexOf(","), sb.length());

		sb.append(")");
		
		return sb.toString();
	}
	
	
	public static String drapTable(Class<?> arg0) {
		// TODO Auto-generated method stub
		String tableName = ClassUtil.getTableName(arg0);
		
		String sql = "drap table if exists " + tableName;
		
		return(sql);
	}
	
	/**
	 * 
	 * @param arg0
	 * @return
	 */
	private static String getColumnType(Class<?> arg0){
		if (String.class == arg0){
			return "TEXT";
		}
		
		if ((Integer.class == arg0) || (Integer.TYPE == arg0)){
			return "INTEGER";
		}
		
		if ((Long.class == arg0) || (Long.TYPE == arg0)){
			return "BIGINT";
		}
		
		if ((Float.class == arg0) || (Float.TYPE == arg0)){
			return "FLOAT";
		}
		
		if ((Short.class == arg0) || (Short.TYPE == arg0)){
			return "INT";
		}
		
		if ((Double.class == arg0) || (Double.TYPE == arg0)){
			return "BOUBLE";
		}
		
		if (Blob.class == arg0){
			return "BLOB";
		}
		
		return "TEXT";
	}
	
	/**
	 * Determine whether there is a table
	 * @param arg0
	 * @return
	 */
	public static String isExistTable(Class<?> arg0){
		String tableName = ClassUtil.getTableName(arg0);
		
		String sql = "select count(*) as c from sqlite_master where type ='table' and name ='" + tableName + "'";
		
		return(sql);
	}
}
